<script setup lang="tsx">
import { reactive, ref, unref, markRaw, shallowRef, provide, type Component } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import Add from './component/Add.vue'
import Modify from './component/Modify.vue'
import Details from './component/Details.vue'
import { ElCollapseTransition, ElSwitch, ElMessage } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { getListApi, modifyStatusApi, delApi, type Row } from '@/api/franchiser'

defineOptions({
  name: 'Shop'
})
const comId = reactive({
  Add: markRaw(Add),
  Modify: markRaw(Modify),
  Details: markRaw(Details)
})
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: 'selection' }
  },
  {
    field: 'name',
    label: '客户名称',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'user_name',
    label: '登录账号',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'real_name',
    label: '联系人',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'mobile',
    label: '联系方式',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'status',
    label: '状态',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: {
      width: '200px',
      slots: {
        default: ({ row }) => {
          return (
            <ElSwitch
              v-model={row.status}
              active-value={1}
              inactive-value={2}
              loading={switchLoading.value}
              beforeChange={() => changeStatus(row)}
            />
          )
        }
      }
    }
  },
  {
    field: 'address',
    label: '经营地址',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'create_time',
    label: '创建时间',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'action',
    width: '260px',
    label: '操作',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: {
      slots: {
        default: ({ row }) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => action(comId['Details'], row)}>
                详情
              </BaseButton>
              <BaseButton type="primary" onClick={() => action(comId['Modify'], row)}>
                编辑
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.count
    }
  },
  fetchDelApi: async () => {
    const res = await delApi({ id: unref(ids).join(',') })
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const showCollapse = ref(false)
let currentAction = shallowRef()
let currentRow = ref<Row | undefined>(undefined)
const action = (component: Component, row?: Row) => {
  currentAction.value = component
  currentRow.value = row
  if (showCollapse.value === false) showCollapse.value = true
}

const closeCollapse = () => {
  showCollapse.value = false
}

const delLoading = ref(false)

const delData = async (row: Row | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: Row) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const switchLoading = ref(false)
const changeStatus = async (row) => {
  const val = {
    '1': 2,
    '2': 1
  }
  switchLoading.value = true
  try {
    const res = await modifyStatusApi({ status: val[row.status], id: row.id })
    if (res) ElMessage.success(res.msg)
    return !!res
  } finally {
    switchLoading.value = false
  }
}

provide('currentRow', currentRow)
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="action(comId['Add'])">新增</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">删除</BaseButton>
    </div>
    <el-collapse-transition>
      <component
        :is="currentAction"
        @close="closeCollapse"
        @get-list="getList"
        v-show="showCollapse"
      />
    </el-collapse-transition>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
